#!/bin/bash
source tools/const.sh

if [ -h "$LINK_FILE" ]; then
  # shellcheck disable=SC2012
  ret=$(ls -l "$LINK_FILE" | awk '{print $NF}')
  real_config_file=$ret
  if [[ "$ret" == *"dev"* || "$ret" == *"local"* ]]; then
    env="dev"
  elif [[ "$ret" == *"test"* ]]; then
    env="test"
  elif [[ "$ret" == *"prod"* ]]; then
    env="prod"
  else
     echo  -e "$RED 无法判断环境，配置文件请包含dev|local,test,prod字样$RESET"
     exit 2
  fi
else
  echo $LINK_FILE
  echo  -e "$RED 没有配置config文件 $RESET"
  echo  -e "$GREEN 执行创建配置文件软连, make createConfFile $RESET"
  exit 2
fi
echo -e "当前环境 = $GREEN$env$RESET"

if [[ -h "$current_dir" ]]; then
  real_app_root_path=$(realpath "$current_dir")
  echo -e "$BOLODGREEN $current_dir 是软连 指向的的实际目录是$real_app_root_path $RESET"
else
  echo -e "$BOLODGREEN $current_dir 是真实目录$RESET"
fi


# 需要在根目录下运行make xxx
function getPortFromRealConfigFile() {
    echo "$real_config_file" | grep -oE '[0-9]+'
}
# 判断配置文件中是否有同样的端口

port=$(getPortFromRealConfigFile)
if [[ ! "$port" -gt 0 ]]; then
  echo -e "$BOLODRED 配置文件名称没有包含端口号$RESET"
  exit 1
fi

echo -e "当前port = $GREEN$port$RESET"
echo -e "当前配置实际文件 = $GREEN$real_config_file$RESET"
if [[ "$env" != "dev" ]]; then
  echo -e "当前守护进程模式 = $GREEN$damonMode$RESET"
fi


if [[ "$ret" == *"dev"* || "$ret" == *"local"* ]]; then
    PID_FILE="${APP_BIN_NAME}.pid"
  elif [[ "$ret" == *"test"* ]]; then
    PID_FILE="/var/run/${APP_BIN_NAME}_${port}.pid"
  elif [[ "$ret" == *"prod"* ]]; then
    PID_FILE="/var/run/${APP_BIN_NAME}_${port}.pid"
  else
     echo  -e "$RED 无法判断环境，配置文件请包含dev|local,test,prod字样$RESET"
     exit 2
  fi






port_count=$(grep "$port" "$LINK_FILE"|grep port|grep -c "$port")
if [ "$port_count" -eq 1 ]; then
    echo "配置文件内容包含了port = $port"
else
    echo -e "$RED 当前实际配置文件内容中包含port和 $port 的行数 不等于1 ，请检查配置文件，看是否创建错软连 $RESET"
    exit 1
fi

# 判断是否存在service文件
if [[ "$damonMode" == "supervisor" ]]; then
  service_name="${env}_${app_name}_${port}_autostart"
  service_file="${supervisor_service_conf}${service_name}.conf"
elif [[ "$damonMode" == "systemd" ]]; then
  service_name="${env}_${app_name}_${port}_autostart"
  service_file="${service_conf}${service_name}.service"
fi

server_bin_all_path="${current_dir}/${APP_BIN_NAME}"

# 通过 nohup 方式运行
function startStock() {
    # echo "current_dir:$current_dir" >> /tmp/stock.log
    # echo "server_bin_all_path:$server_bin_all_path" >> /tmp/stock.log
    cd "${current_dir}" && nohup "${server_bin_all_path}" &
}

function  getSupervisorctlStatusRunningNum() {
  supervisorctl status "${service_name}" | grep 'RUNNING'  | grep -c -v grep
}
function supervisorctlStatus() {
#  supervisorctl status "${service_name}"
  supervisorctlStatusAddColor
}

#30 black
#31 red
#32 green
#33 yellow
#34 blue
#35 purple
#36 cyan
#37 white
#
#命令如：export GREP_OPTIONS='--color=auto' GREP_COLOR='31'

function supervisorctlStatusAddColor() {
  num=$(supervisorctl status "${service_name}" | grep -c 'RUNNING')
  if [[ "$num" == 1 ]]; then
    export GREP_COLOR='32' # green
    supervisorctl status "${service_name}" | grep -v grep | grep --color 'RUNNING'
  else
    num=$(supervisorctl status "${service_name}" | grep -c 'STOPPED')
    echo -e "${BOLODRED}服务不在running$RESET"
    if [[ "$num" == 1 ]]; then
      export GREP_COLOR='31' #red
      supervisorctl status "${service_name}" | grep -v grep | grep --color 'STOPPED'
    else
      echo -e "${BOLODRED}服务既不是running也不是stopped$RESET"
      supervisorctl status "${service_name}"
    fi
  fi
}

function getServerBinAllPathNum() {
    ps aux|grep -v "\.log"|grep -v tail|grep -v grep|grep -c "${server_bin_all_path}"
}
function psServerBinAllPath() {
    export GREP_COLOR='32' # green
    ps aux|grep -v "\.log"|grep -v tail|grep -v grep|grep --color "${server_bin_all_path}"
}

function getGrepPidFileNum() {
    ps aux | grep $(getPidFromPidFile) | grep -c -v grep
}
function getPidFromPidFile() {
    cat "$PID_FILE"
}



function getPortCountFromConfigFile() {
    grep "$port" "$LINK_FILE"|grep -c port
}

function getPidFIleCountFromConfigFile() {
    grep "$port" "$LINK_FILE"|grep -c pidfile
}

function mySystemdStatus() {
  if [[ "$env" == "dev" ]]; then
    echo "$env"环境没有systemd
  elif [[ "$env" == "test" || "$env" == "prod" ]]; then
    echo "==================================================================================="
    echo -e "$BOLD_WHITE 查看服务状态是否正常...$RESET"
    num=$(systemctl status "${service_name}" | grep 'active (running'  | grep -v grep | wc -l)
    if [[ $num -eq 0 ]]; then
      echo -e "${RED}服务不在running$RESET"
    else
      echo -e "${GREEN}服务在running$RESET"
    fi
    systemctl status "${service_name}"
  fi
}

#function autostartProcessIsExist() {
#    num=$(ps aux|grep -v "\.log"|grep -v tail|grep -v grep|grep -c "autostat")
#}

function mySupervisorStatus() {
  if [[ "$env" == "dev" ]]; then
    echo "$env"环境没有supervisor
  elif [[ "$env" == "test" || "$env" == "prod" ]]; then
    echo "========================================================================================================================"
    echo ""
    echo -e "$CYAN 查看 ${BOLDMAGENTA}supervisor$CYAN 服务状态是否正常...$RESET"
    num=$(getSupervisorctlStatusRunningNum)
    if [[ $num -eq 0 ]]; then
      pid="0"
    else
      echo -e "${BOLODGREEN}服务在running$RESET"
      pid=$(supervisorctlStatus| awk '{print $4}'|sed 's/,//g')
    fi
    supervisorctlStatus

    if [[ "$pid" == "0" ]]; then
      echo ""
    else
      echo -e "                                 ${GREEN}-----------------"
      echo  -e "                                   ↓"
      echo  -e "           ←------------------------"
      echo  -e "           ↓$RESET"
      export GREP_COLOR='32' # green
      ps aux | grep "auto" | grep -v grep | grep --color "$pid"
      echo ""
    fi


    echo "================================================================================================================================"
    echo ""
    echo -e "$CYAN 查看 ${BOLDMAGENTA} systemd 守护的服务 ${BOLDMAGENTA} supervisor$CYAN 状态是否正常...$RESET"
    num=$(systemctl status supervisord | grep 'active (running'  | grep -v grep | wc -l)
    if [[ $num -eq 0 ]]; then
      echo -e "${BOLODRED}systemd 监控的supervisor，不在running$RESET"
    else
      echo -e "${BOLODGREEN}systemd 监控的supervisor，在running$RESET"
    fi
    systemctl status supervisord
    echo "---------------------------------------------------------------------------------------------------------------------------------"
    echo ""
  fi
}


function rollbackAfterRestart() {
  # 回滚后重启进程
  num=$(getServerBinAllPathNum)
  if [[ $num -eq 0 ]]; then
    echo -e "${BOLODRED}进程不存在$RESET"
    startStock
  else
    echo "---------------------------------------------------------------------"
    echo -e "${BOLODGREEN}进程存在, make restart $RESET"
    echo "current_dir:$current_dir"
    cd "$current_dir" && make restart
  fi
  psServerBinAllPath
}


function validCurrDirIsLink() {
  if [[ "$env" == "test" || "$env" == "prod" ]]; then
    if [[ ! -h $current_dir ]]; then
      echo -e "$BOLODRED $current_dir 不是软连，该命令仅支持软连$RESET"
      exit 1
    fi
  fi
}


function create_log_dir() {
  if [[ "$env" == "dev" ]]; then
    echo -e "$BOLODRED  当前环境是dev，请手动创建log目录$RESET"
    exit 1
  fi

  if [[ "$env" == "test" || "$env" == "prod" ]]; then
    log_real_dir="/data/log/$app_root_path"



    if [[ ! -e "$log_real_dir" ]]; then
      mkdir -p "$log_real_dir"
      if [[ $? -ne 0 ]]; then
        echo -e "$BOLODRED 创建目录失败，请手动创建目录 $log_real_dir $RESET"
        exit 1
      else
        echo -e "$BOLODGREEN 创建目录成功 $log_real_dir $RESET"
      fi
    else
      echo -e "$BOLODGREEN 目录已存在 $log_real_dir $RESET"
    fi

    if [[ -e "$LOG_FILE" ]]; then
      echo  -e "$RED $LOG_FILE  log文件存在,但不是软连，移动log到新目录 $RESET"
      mv "$LOG_FILE"/* "$log_real_dir"
      rm -rf "$LOG_FILE"
    fi

    ln -s "$log_real_dir" "$LOG_FILE"
    ls -dal "$LOG_FILE"
    echo -e "已创建快捷方式 $GREEN${LOG_FILE}$RESET ,指向文件 $GREEN${log_real_dir}$RESET"
  else
    echo -e "$BOLODRED 当前环境是 $env ，请手动处理"
  fi
}